package org.iabako.client.ui.form.business.sale.make;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.tools.Messages;
import org.iabako.client.ui.form.business.sale.SendInvoiceByEmail;
import org.iabako.client.ui.layout.field.InputText;
import org.iabako.client.ui.layout.field.InputTextDate;
import org.iabako.client.ui.layout.widget.installment.InstallmentsDefinitionForm;
import org.iabako.client.ui.layout.widget.sale.SaleRecap;
import org.iabako.client.ui.page.business.sale.QuoteSearch;
import org.iabako.client.ui.page.business.sale.SaleSearch;
import org.iabako.client.user.AuthenticateUserProvider;
import org.iabako.shared.entity.business.Client;
import org.iabako.shared.entity.business.Sale;
import org.iabako.shared.entity.business.SaleProductService;
import org.iabako.shared.entity.enumeration.*;
import org.iabako.shared.iservice.business.SaleServiceAsync;
import org.iabako.shared.iservice.function.InvoiceGeneratorServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.List;

/**
 * Created by jose on 24/10/14.
 */
public class SaleMakeConfirmation extends SaleMakeSubForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, SaleMakeConfirmation> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    protected final SaleServiceAsync saleServiceAsync = SaleServiceAsync.Util.getInstance();
    protected final InvoiceGeneratorServiceAsync invoiceGeneratorServiceAsync = InvoiceGeneratorServiceAsync.Util.getInstance();

    @UiField
    InputTextDate saleDate;
    @UiField
    SaleRecap saleRecap;
    @UiField
    public InputText number;
    @UiField
    FormPanel invoiceGeneratorForm;
    @UiField
    InputElement invoiceGeneratorFileToken;

    public SaleMakeConfirmation() {
        initWidget(binderForm.createAndBindUi(this));

        setHandlers();
    }

    public void initialize() {
        initialize(saleMakeForm.client,
                saleMakeForm.getSaleProductServiceList(),
                (PaymentType) saleMakeForm.saleMakePaymentDefinition.paymentType.getValue(),
                (PaymentMethod) saleMakeForm.saleMakePaymentDefinition.paymentMethod.getEnumValue(),
                saleMakeForm.saleMakePaymentDefinition.installmentsForm.customClone(saleMakeForm.saleMakeConfirmation.saleRecap.saleNote));
    }

    @Override
    protected void restoreDraft() {
        Sale sale = (Sale) saleMakeForm.entity;
        if (((Sale) saleMakeForm.entity).getSaleStep() == SaleStep.confirmation) {
            saleMakeForm.saleMakeConfirmation.initialize(saleMakeForm.client, saleMakeForm.getSaleProductServiceList(),
                    (PaymentType) saleMakeForm.saleMakePaymentDefinition.paymentType.getValue(),
                    (PaymentMethod) saleMakeForm.saleMakePaymentDefinition.paymentMethod.getEnumValue(),
                    saleMakeForm.saleMakePaymentDefinition.installmentsForm.
                            customClone(saleMakeForm.saleMakeConfirmation.saleRecap.saleNote));
        }
        saleMakeForm.contentPanel.setVisible(true);
        saleMakeForm.waitIconPanel.setVisible(false);
        saleMakeForm.recoverQuote.setVisible(sale.getStatus() == FinancialStatusSale._3_quote_discard);
    }

    public void activateQuoteMode() {
        number.setHelpInfo("quote_information_form_number_help");
        saleDate.setInputTitle("invoice_quote_date");
        saleRecap.whoLabel.setLabel(Messages.getLabel(SaleStep.who.getLabelKey().replace("sale", "quote")));
        saleRecap.whatLabel.setLabel(Messages.getLabel(SaleStep.what.getLabelKey().replace("sale", "quote")));

        saleMakeForm.quoteDownloadAction.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                if (!saleMakeForm.uiValidation()) {
                    return;
                }
                Sale sale = updateSaleForInvoiceGeneration();
                generateInvoice(sale);
            }
        });

        saleMakeForm.quoteSendEmailAction.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                if (!saleMakeForm.uiValidation()) {
                    return;
                }
                Sale sale = updateSaleForInvoiceGeneration();
                SendInvoiceByEmail sendInvoiceByEmail = new SendInvoiceByEmail(sale, null, null, true);
                NavigationController.getInstance().goTo(sendInvoiceByEmail);
            }
        });

        saleMakeForm.transformQuoteToSale.getButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                saleMakeForm.quoteTransformToSaleMode = true;
                saleMakeForm.validate(true);
            }
        });

        saleMakeForm.discardQuote.getButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                if (saleMakeForm.entity == null) {
                    //Quote has not been saved yet
                    NavigationController.getInstance().closePopup(false);
                    return;
                }
                ((Sale) saleMakeForm.entity).setStatus(FinancialStatusSale._3_quote_discard);
                saleMakeForm.validate(true);
            }
        });
        saleMakeForm.recoverQuote.getButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                ((Sale) saleMakeForm.entity).setStatus(FinancialStatusSale._0_quote_draft);
                saleMakeForm.validate(true);
            }
        });
    }

    private Sale updateSaleForInvoiceGeneration() {
        Sale sale = (Sale) saleMakeForm.getEntity();
        sale.setSaleStep(saleMakeForm.saleWorkflow.getSelectedSaleStep());
        if (sale.getStatus() != FinancialStatusSale._2_quote_transformed && sale.getStatus() != FinancialStatusSale._3_quote_discard) {
            sale.setStatus(FinancialStatusSale._1_quote_generated);
        }
        return sale;
    }

    private void generateInvoice(Sale sale) {
        invoiceGeneratorServiceAsync.generateInvoiceForQuote(sale, sale.getProductsServices(), new IabakoAsyncCallback<String>() {
            public void onSuccess(String result) {
                invoiceGeneratorForm.setMethod("GET");
                invoiceGeneratorFileToken.setValue(result);
                invoiceGeneratorForm.submit();

                AuthenticateUserProvider.getTrackingPanel().refresh(TrackingType.quoteDownloaded);
                refreshQuoteSearch();
                super.onSuccess(result);
            }
        });
    }

    private void refreshQuoteSearch() {
        if (NavigationController.getInstance().getRootPage().pageContentComposite instanceof QuoteSearch) {
            //If rootPage is SaleSearch, we have to refresh search
            ((SaleSearch) NavigationController.getInstance().
                    getRootPage().pageContentComposite).saleSearchForm.searchForm.search(false);
        }
    }

    public void activateSaleEnMasse() {
        number.setVisible(false);
        saleRecap.whoLinkModification.setVisible(false);
        saleRecap.clientListOfSaleEnMasse.setVisible(true);
        saleRecap.clientListOfSaleEnMasse.setLabel(Messages.getLabel("sales_en_masse_see_client_list_link", saleMakeForm.clientList.size() + ""));

        saleRecap.clientListOfSaleEnMasse.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                saleMakeForm.showDialogBoxWithClientList();
            }
        });
    }

    class ModifyHandler implements ClickHandler {
        SaleStep stepToGo;

        ModifyHandler(SaleStep stepToGo) {
            this.stepToGo = stepToGo;
        }

        public void onClick(ClickEvent event) {
            saleMakeForm.popup.actionButton.setVisible(false);
            saleMakeForm.goTo(stepToGo);
        }
    }

    private void setHandlers() {
        saleRecap.whoLabel.setVisible(true);
        saleRecap.whatLabel.setVisible(true);
        saleRecap.howLabel.setVisible(true);

        saleRecap.whoLinkModification.setVisible(true);
        saleRecap.whatLinkModification.setVisible(true);
        saleRecap.howLinkModification.setVisible(true);

        saleRecap.whoLinkModification.getLabel().addClickHandler(new ModifyHandler(SaleStep.who));
        saleRecap.whatLinkModification.getLabel().addClickHandler(new ModifyHandler(SaleStep.what));
        saleRecap.howLinkModification.getLabel().addClickHandler(new ModifyHandler(SaleStep.how));
    }

    public void initialize(Client client, List<SaleProductService> productServiceList,
                           PaymentType paymentType, PaymentMethod paymentMethod, InstallmentsDefinitionForm installmentsDefinitionForm) {

        saleMakeForm.popup.actionButton.setVisible(true);

        if (paymentType == PaymentType.onePayment) {
            saleRecap.saleNote.setHtmlLabel(Messages.getLabel("sale_make_one_payment_note", GenericTools.formatAmount(saleMakeForm.saleMakeProductServiceChoice.totalPrice + "")));
        }

        saleRecap.initialize(client, productServiceList, paymentType, paymentMethod, installmentsDefinitionForm, saleMakeForm.quoteMode);
        if (saleMakeForm.saleEnMasse) {
            saleRecap.noClientNote.setVisible(false);
        }
        Sale sale = (Sale) saleMakeForm.entity;
        if (saleMakeForm.quoteMode) {
            saleRecap.handleGoToQuote(sale);
        }
        if (sale != null && (sale.getStatus() == FinancialStatusSale._2_quote_transformed || sale.getStatus() == FinancialStatusSale._3_quote_discard)) {
            enableModificationMode(false);
        } else {
            enableModificationMode(true);
        }
    }

    public void enableModificationMode(boolean isModification) {
        saleMakeForm.saleWorkflow.setVisible(isModification);
        saleRecap.whoLinkModification.setVisible(isModification);
        saleRecap.whatLinkModification.setVisible(isModification);
        saleRecap.howLinkModification.setVisible(isModification);
        number.setEnabled(isModification);
        saleDate.setEnabled(isModification);
        saleMakeForm.popup.actionButton.setVisible(isModification);
        if (!isModification) {
            saleMakeForm.quoteSendEmailAction.setStyleName(saleMakeForm.quoteSendEmailAction.getStyleName().replace("quotedrafbutton", ""));
            saleMakeForm.quoteDownloadAction.setStyleName(saleMakeForm.quoteDownloadAction.getStyleName().replace("quotedrafbutton", ""));
        } else {
            saleMakeForm.quoteSendEmailAction.setStyleName(saleMakeForm.quoteSendEmailAction.getStyleName() + " quotedrafbutton");
            saleMakeForm.quoteDownloadAction.setStyleName(saleMakeForm.quoteDownloadAction.getStyleName() + " quotedrafbutton");
        }

        if (saleMakeForm.quoteMode) {
            saleMakeForm.transformQuoteToSale.setVisible(isModification);
            saleMakeForm.discardQuote.setVisible(isModification);
        }

        saleRecap.handleGoToQuote((Sale) saleMakeForm.entity);
    }

    @Override
    protected void validateForm() {
    }

    @Override
    protected void goBackAction() {
    }
}
